package com.yjf.ljr.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.SimpleFormatter;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.RedPacketDataClass;
import com.yjf.ljr.dataclass.RedPacketDataClass.RedPacketInfo;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.view.XListView;
import com.yjf.ljr.view.XListView.IXListViewListener;

public class RedPacketActivity extends IjActivity {

	private static final String RED_PACKET_USABLE = "AVAILABLE";
	private static final String RED_PACKET_USED = "FINISH";
	private static final String RED_PACKET_EXPIRED = "EXPIRE";

	@ID("red_packet_type")
	private RadioGroup redPacketType;
	@ID("red_packet_list")
	private XListView redPacketList;

	@ID("used_red_packet_list")
	private XListView usedRedPacketList;
	@ID("expired_red_packet_list")
	private XListView expiredRedPacketList;

	private String redPacketCurrentType = RED_PACKET_USABLE;
	private CommonAdapter redPacketAdapter;
	private List<RedPacketInfo> redPacketDatas;

	private CommonAdapter usedRedPacketAdapter;
	private List<RedPacketInfo> usedRedPacketDatas;
	private CommonAdapter expiredRedPacketAdapter;
	private List<RedPacketInfo> expiredRedPacketDatas;

	private boolean mIsLoadingMore = false;
	private final int mPageSize = 10;
	private int mCurPage = 1;
	private int usedCurPage = 1;
	private int expiredCurPage = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_red_packet);
		initControls();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void initControls() {
		setLeftBtnClick();
		setTitleStr(getString(R.string.red_packet_manage));
		redPacketCurrentType = RED_PACKET_USABLE;

		redPacketDatas = new ArrayList<RedPacketInfo>();
		redPacketAdapter = new CommonAdapter(this, redPacketDatas, R.layout.item_red_packet, ViewHolder.class,
				mHandleCallBack);
		redPacketList.setAdapter(redPacketAdapter);
		redPacketList.setPullLoadEnable(true);
		redPacketList.setPullRefreshEnable(true);
		redPacketList.mFooterView.hide();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		redPacketList.setRefreshTime(sdf.format(new Date()));
		redPacketList.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				if (mIsLoadingMore) {
					return;
				}
				mCurPage = 1;
				mIsLoadingMore = true;
				new RedPacketListTask(RED_PACKET_USABLE, mPageSize, mCurPage, false).execute();
			}

			@Override
			public void onLoadMore() {
				if (mIsLoadingMore) {
					return;
				}
				mIsLoadingMore = true;
				new RedPacketListTask(RED_PACKET_USABLE, mPageSize, ++mCurPage, true).execute();
			}
		});

		usedRedPacketDatas = new ArrayList<RedPacketInfo>();
		usedRedPacketAdapter = new CommonAdapter(this, usedRedPacketDatas, R.layout.item_red_packet, ViewHolder.class,
				mHandleCallBack);
		usedRedPacketList.setAdapter(usedRedPacketAdapter);
		usedRedPacketList.setPullLoadEnable(true);
		usedRedPacketList.setPullRefreshEnable(true);
		usedRedPacketList.mFooterView.hide();
		usedRedPacketList.setRefreshTime(sdf.format(new Date()));
		usedRedPacketList.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				if (mIsLoadingMore) {
					return;
				}
				usedCurPage = 1;
				mIsLoadingMore = true;
				new RedPacketListTask(RED_PACKET_USED, mPageSize, usedCurPage, false).execute();
			}

			@Override
			public void onLoadMore() {
				if (mIsLoadingMore) {
					return;
				}
				mIsLoadingMore = true;
				new RedPacketListTask(RED_PACKET_USED, mPageSize, ++usedCurPage, true).execute();
			}
		});

		expiredRedPacketDatas = new ArrayList<RedPacketInfo>();
		expiredRedPacketAdapter = new CommonAdapter(this, expiredRedPacketDatas, R.layout.item_red_packet,
				ViewHolder.class, mHandleCallBack);
		expiredRedPacketList.setAdapter(expiredRedPacketAdapter);
		expiredRedPacketList.setPullLoadEnable(true);
		expiredRedPacketList.setPullRefreshEnable(true);
		expiredRedPacketList.mFooterView.hide();
		expiredRedPacketList.setRefreshTime(sdf.format(new Date()));
		expiredRedPacketList.setXListViewListener(new IXListViewListener() {
			@Override
			public void onRefresh() {
				if (mIsLoadingMore) {
					return;
				}
				expiredCurPage = 1;
				mIsLoadingMore = true;
				new RedPacketListTask(RED_PACKET_EXPIRED, mPageSize, expiredCurPage, false).execute();
			}

			@Override
			public void onLoadMore() {
				if (mIsLoadingMore) {
					return;
				}
				mIsLoadingMore = true;
				new RedPacketListTask(RED_PACKET_EXPIRED, mPageSize, ++expiredCurPage, true).execute();
			}
		});

		redPacketType.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				// 可用
				case R.id.red_packet_usable:
					redPacketCurrentType = RED_PACKET_USABLE;
					break;
				// 已用
				case R.id.red_packet_used:
					redPacketCurrentType = RED_PACKET_USED;
					break;
				// 已过期
				case R.id.red_packet_expired:
					redPacketCurrentType = RED_PACKET_EXPIRED;
					break;
				default:
					break;
				}
				showDataByType();
			}
		});

		showDataByType();
	}

	public void showDataByType() {
		if (redPacketCurrentType.equalsIgnoreCase(RED_PACKET_USABLE)) {
			usedRedPacketList.setVisibility(View.GONE);
			expiredRedPacketList.setVisibility(View.GONE);
			redPacketList.setVisibility(View.VISIBLE);
			if (redPacketDatas.size() < 1) {
				showProgressDialog();
				new RedPacketListTask(RED_PACKET_USABLE, mPageSize, mCurPage, false).execute();
			}
		} else if (redPacketCurrentType.equalsIgnoreCase(RED_PACKET_EXPIRED)) {
			redPacketList.setVisibility(View.GONE);
			usedRedPacketList.setVisibility(View.GONE);
			expiredRedPacketList.setVisibility(View.VISIBLE);
			if (expiredRedPacketDatas.size() < 1) {
				showProgressDialog();
				new RedPacketListTask(RED_PACKET_EXPIRED, mPageSize, expiredCurPage, false).execute();
			}
		} else {
			redPacketList.setVisibility(View.GONE);
			expiredRedPacketList.setVisibility(View.GONE);
			usedRedPacketList.setVisibility(View.VISIBLE);
			if (usedRedPacketDatas.size() < 1) {
				showProgressDialog();
				new RedPacketListTask(RED_PACKET_USED, mPageSize, usedCurPage, false).execute();
			}
		}

	}

	public static class ViewHolder {
		private TextView redPacketAmount;
		private TextView redPacketExpiryDate;
		private TextView redPacketUseCondition;
		private TextView redPacketSource;
		private TextView redPacketUseAmount;
		private LinearLayout redPacketItem;
		private TextView couponType;
	}

	private HandleCallBack mHandleCallBack = new HandleCallBack() {

		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			RedPacketInfo info = (RedPacketInfo) item;
			ViewHolder h = (ViewHolder) holder;

			if (!TextUtils.isEmpty(info.type)) {
				h.couponType.setText(info.type);
				if(info.type.equals("红包") || info.type.contains("红包")) {
					h.couponType.setBackgroundResource(R.drawable.red_packet_bg);
					h.redPacketItem.setBackgroundResource(R.drawable.red_packet_item_bg_shape);
				} else if(info.type.equals("体验金") || info.type.equals("虚拟体验金")) {
					h.couponType.setBackgroundResource(R.drawable.experience_bg);
					h.redPacketItem.setBackgroundResource(R.drawable.red_packet_experience_item_bg_shape);
				} else if (info.type.equals("加息劵") || info.type.contains("加息劵") || info.type.contains("加息卷")) {
					h.couponType.setBackgroundResource(R.drawable.querygiftlist_bg);
					h.redPacketItem.setBackgroundResource(R.drawable.interest_rate_coupon_item_bg_shape);
//					h.redPacketItem.setBackgroundResource(R.drawable.red_packet_gain_item_bg_shape);
				} else {
					h.couponType.setBackgroundResource(R.drawable.gain_coupon_bg);
					h.redPacketItem.setBackgroundResource(R.drawable.red_packet_gain_item_bg_shape);
				}
			}

			SpannableString amountResult = getRedPacketAmount(RedPacketActivity.this.getString(R.string.red_packet_amount, info.amount));
			if (info.type.equals("加息劵") || info.type.contains("加息劵") || info.type.contains("加息")) {
				String tempStr = "+" + info.rateOfYear + "%";
				SpannableString tempSpan = getRedPacketAmount(tempStr);
				h.redPacketAmount.setText(tempSpan);
			} else {
				h.redPacketAmount.setText((amountResult == null) ? "" : amountResult);
			}
			String date = info.endDate;
			String useDate = info.rawUpdateTime;
			if (!TextUtils.isEmpty(info.endDate)) {
				String[] dates = info.endDate.trim().split(" ");
				if (dates.length > 1) {
					date = dates[0];
				}
			}

			if (!TextUtils.isEmpty(info.rawUpdateTime)) {
				String[] useDates = info.rawUpdateTime.trim().split(" ");
				if (useDates.length > 1) {
					useDate = useDates[0];
				}
			}

			if (info.status.equalsIgnoreCase(RED_PACKET_EXPIRED)) {
				h.redPacketExpiryDate.setVisibility(View.VISIBLE);
				h.redPacketExpiryDate.setText(RedPacketActivity.this.getString(R.string.red_packet_expired_date, date));
			} else if (info.status.equalsIgnoreCase(RED_PACKET_USED)) {
				h.redPacketExpiryDate.setVisibility(View.VISIBLE);
				h.redPacketExpiryDate.setText(RedPacketActivity.this.getString(R.string.red_packet_used_date, useDate));
			} else {
				h.redPacketExpiryDate.setVisibility(View.GONE);
				// h.redPacketExpiryDate.setText(RedPacketActivity.this.getString(R.string.red_packet_validity,
				// date));
			}

			h.redPacketSource.setText(info.giftName);
			double useCondition = AppUtil.moneyToNum(info.useAmount);
			if (info.type.equals("加息劵") || info.type.contains("加息劵") || info.type.contains("加息")) {
				// h.redPacketUseCondition.setText(info.useType + info.amount +
				// "元可用");
				h.redPacketUseCondition.setVisibility(View.GONE);
			} else {
				h.redPacketUseCondition.setVisibility(View.VISIBLE);
				if (useCondition > 0) {
					h.redPacketUseCondition.setText(RedPacketActivity.this.getString(R.string.red_packet_use_condition,
							info.useAmount));
					h.redPacketUseCondition.setVisibility(View.VISIBLE);
				} else {
					h.redPacketUseCondition.setVisibility(View.GONE);
				}
			}

			double usedAmount = AppUtil.moneyToNum(info.usedAmount);

			if (usedAmount > 0 && !info.status.equals(RED_PACKET_USED)) {
				h.redPacketUseAmount.setText(RedPacketActivity.this.getString(R.string.red_packet_used_amount,
						info.usedAmount));
				h.redPacketUseAmount.setVisibility(View.VISIBLE);
			} else {
				h.redPacketUseAmount.setVisibility(View.GONE);
			}
		}
	};

	private SpannableString getRedPacketAmount(String amount) {
		if (amount != null) {
			SpannableString result = new SpannableString(amount);
			result.setSpan(new RelativeSizeSpan(1.5f), 0, amount.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			result.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, amount.length() - 1,
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			return result;
		} else {
			return null;
		}
	}

	class RedPacketListTask extends AsyncTask<Void, Void, String> {

		private RedPacketDataClass dc = new RedPacketDataClass();

		private String status = RED_PACKET_USABLE;

		private int pageSize;
		private int curPage;
		private boolean isAdd = false;

		public RedPacketListTask(String status, int pageSize, int curPage, boolean isAdd) {
			this.status = status;
			this.pageSize = pageSize;
			this.curPage = curPage;
			this.isAdd = isAdd;
		}

		@Override
		protected String doInBackground(Void... params) {
			RequestObject reqObj = new RequestObject();
			reqObj.method = "queryGiftList";
			reqObj.map.put("pageSize", pageSize);
			reqObj.map.put("pageNumber", curPage);
			if (!TextUtils.isEmpty(status) && status.equals(RED_PACKET_USABLE)) {
				reqObj.map.put("tradeType", "ORIGINAL");
			}
			reqObj.map.put("status", status);
			return requestDataAndGetErrorMsg(reqObj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			redPacketList.stopRefresh();
			redPacketList.stopLoadMore();
			usedRedPacketList.stopRefresh();
			usedRedPacketList.stopLoadMore();
			expiredRedPacketList.stopRefresh();
			expiredRedPacketList.stopLoadMore();
			mIsLoadingMore = false;
			if ("-1".equals(dc.code)) {
				loginWebview();
				return;
			}
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				if (redPacketCurrentType.equalsIgnoreCase(RED_PACKET_USABLE)) {
					if (!isAdd) {
						redPacketDatas.clear();
						redPacketAdapter.notifyDataSetChanged();
					}
					if (dc.redPacketList != null && dc.redPacketList.size() > 0) {
						redPacketDatas.addAll(dc.redPacketList);
						redPacketAdapter.notifyDataSetChanged();
						if (redPacketDatas.size() <= (dc.totalPage - 1) * pageSize) {
							redPacketList.mFooterView.show();
						} else {
							redPacketList.mFooterView.hide();
						}
					} else {
						showToast(getString(R.string.no_data_now));
					}
				} else if (redPacketCurrentType.equalsIgnoreCase(RED_PACKET_EXPIRED)) {
					if (!isAdd) {
						expiredRedPacketDatas.clear();
						expiredRedPacketAdapter.notifyDataSetChanged();
					}
					if (dc.redPacketList != null && dc.redPacketList.size() > 0) {
						expiredRedPacketDatas.addAll(dc.redPacketList);
						expiredRedPacketAdapter.notifyDataSetChanged();

						if (expiredRedPacketDatas.size() <= (dc.totalPage - 1) * pageSize) {
							expiredRedPacketList.mFooterView.show();
						} else {
							expiredRedPacketList.mFooterView.hide();
						}
					} else {
						showToast(getString(R.string.no_data_now));
					}
				} else {
					if (!isAdd) {
						usedRedPacketDatas.clear();
						usedRedPacketAdapter.notifyDataSetChanged();
					}
					if (dc.redPacketList != null && dc.redPacketList.size() > 0) {
						usedRedPacketDatas.addAll(dc.redPacketList);
						usedRedPacketAdapter.notifyDataSetChanged();

						if (usedRedPacketDatas.size() <= (dc.totalPage - 1) * pageSize) {
							usedRedPacketList.mFooterView.show();
						} else {
							usedRedPacketList.mFooterView.hide();
						}
					} else {
						showToast(getString(R.string.no_data_now));
					}
				}

			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CommonData.REQUEST_CODE_LOGIN:
				showDataByType();
				break;

			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		return false;
	}

}
